define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/op/models'),
        user_models = require('js/apps/console/models'),
        utils = require('js/utils/tools'),
        tz = require('js/utils/tz'),
        cookie = require('js/utils/cookie'),
        app = Backbone.history;
    require('datetimepicker');
    require('multiselect');
    require('magnific');
    require('jquery-ui');

    var WithdrawControlListView = Backbone.View.extend({
        events: {
            'click #search': 'doSearch',
            'change #selectAll': 'selectAll',
            'change .check-row': 'checkRow',
            'click #export': 'exportData',
            'click #closeBtn' : 'closeUpdateLimitDialog',
            'click #switchSearchTime': 'changeSearchTime',
            'click #saveBtn' :  'setCurrentLimitCash'
        },

        initialize: function (options) {
            this.options = options;
            this.collection = new models.WithdrawCollection();
            this.user_collection = new user_models.UserCollection();
            this.checkedIds = [];
            this.collection.bind('change remove reset', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        exportData: function () {
            notify.warning('警告', '导出中，请等待');
            utils.exportData(this.collection.url, this._getSearchOption());
        },
        closeUpdateLimitDialog: function(){
            $("#withdrawLimitDialog").hide();
            $("#newLimitCash").val('');
        },
        getCurrentLimitCash: function(){
            var that = this;
            $.ajax({
                url: '/admin/withdraw/get_limit/',
                type: 'GET',
                headers: {
                    'X-AUTH-USER': cookie.getCookie('bigbang_user_id'),
                    'X-AUTH-TOKEN': cookie.getCookie('bigbang_user_token'),
                    'content-type': 'application/json'
                }
            }).done(function (resp) {
                var amount = resp.data.amount;
                $("#currentlimitCash").text(amount);
                $("#withdrawLimitDialog").show();

            }).fail(function (resp) {
                console.log(JSON.stringify(resp));
            });
        },
        setCurrentLimitCash: function(){
            var that = this;

            $.ajax({
                url: '/admin/withdraw/set_limit/',
                type: 'POST',
                headers: {
                    'X-AUTH-USER': cookie.getCookie('bigbang_user_id'),
                    'X-AUTH-TOKEN': cookie.getCookie('bigbang_user_token')
                },
                data: JSON.stringify({
                    'amount': $("#newLimitCash").val()
                })
            }).done(function (resp) {
                notify.success('提示', '刷新成功！');
                that.closeUpdateLimitDialog();

            }).fail(function (resp) {
                notify.error('错误', '刷新失败！');
                console.log(JSON.stringify(resp));
                that.closeUpdateLimitDialog();
            });

        },
        selectAll: function (e) {
            var checked = $(e.target).is(':checked');
            $('.check-row').prop('checked', checked);
            if (!checked) {
                this.checkedIds = [];
            } else {
                this.checkedIds = this.collection.pluck('id');
            }
            $('#selectTips').html('已选中' + this.checkedIds.length + '个');
        },
        checkRow: function (e) {
            var tr = $(e.target).closest('tr'),
                id = tr.data('id');
            if ($(e.target).is(':checked')) {
                this.checkedIds.push(id);
            } else {
                this.checkedIds = _.without(this.checkedIds, id);
            }
            $('#selectTips').html('已选中' + this.checkedIds.length + '个');
        },
        changeSearchTime: function () {
            var $item = $('#switchSearchTime');
             console.log($item.html());
            if ($item.html() == '申请时间(点击切换)') {
                $item.html('提现时间(点击切换)');
                $('#searchUpdatedAt').show().find('input').each(function () {
                    $(this).val('');
                });;
                $('#searchCreatedAt').hide().find('input').each(function () {
                    $(this).val('');
                });
            } else {
                $item.html('申请时间(点击切换)');
                $('#searchCreatedAt').show().find('input').each(function () {
                    $(this).val('');
                });;
                $('#searchUpdatedAt').hide().find('input').each(function () {
                    $(this).val('');
                });
            }
        },
        _getSearchOption: function () {
            var options = {};
            var searched = utils.getAllInput('#sidebar_right');
            searched.user_id = $('#searchUid').val();
            searched.target_type = parseInt($('#searchType').val());
            searched.risk_type = parseInt($('#searchRiskType').val());
            searched.status = parseInt($('#searchStatus').val());
            console.log(searched.status)
            
            var selected_input = ['target_type', 'risk_type', 'check_status', 'status'],
                regular_input = ['id', 'user_id'],
                time_input = ['created_at', 'updated_at'];
            _.each(selected_input.concat(regular_input).concat(time_input), function (k) {
                if (selected_input.includes(k)) {
                    if (searched[k] != -1) options[k] = searched[k];
                } else if (searched[k]) {
                    options[k] = searched[k];
                    if (time_input.includes(k)) searched.time_field = k;
                }
            });
            utils.saveSearched('op/withdraw_control', searched);
            return options;
        },
        doSearch: function () {
            var options = this._getSearchOption();
            options.$page = 1;
            options.$size = 300;
            options.is_fresh = 0;
            options._ = new Date().getTime();
            app.navigate(utils.composeQueryString('#op/withdraw_control/', options), {
                trigger: true
            });
        },
        renderWithData: function () {
            var user_dict = {};
            _.each(this.user_collection.toJSON(), function (k) {
                user_dict[k.id] = k.nickname;
            });
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                user_dict: user_dict,
                searched: utils.getSearched('op/withdraw_control')
            }));
            var that = this;
            $('.modify-item').magnificPopup({
                items: {
                    src: '#editWithdrawPanel',
                    type: 'inline'
                },
                midClick: true,
                closeOnBgClick: false,
                callbacks: {
                    beforeOpen: function () {
                        var data_id = $(this.st.el).closest('tr').data('id'),
                            choosen = that.collection.get(data_id);
                        
                        $('#withdraw_created_time').html(choosen.get('created_at'));
                        $('#detailId').text(choosen.get('id'));
                        $('#detailUserId').text(choosen.get('user_id'));
                        $('#detailUserLevel').text(choosen.get('user_level'));
                        $('#detailCashPrice').text(choosen.get('price'));
                        $('#detailBalance').text(choosen.get('balance'));
                        $('#detailType').text(WITHDRAW_TYPE[choosen.get('target_type')]);
                        $('#detailCreatedAt').text(choosen.get('created_at'));
                        if (choosen.get('status') === 2) {
                            $('#detailCalCashPrice').text(choosen.get('real_price'));
                        } else {
                            $('#detailCalCashPrice').text(choosen.get('real_cash_price'));
                        }
                        
                        var detailInfo;
                        var detail_info = choosen.get('withdraw_info');
                        var withdraw_info = choosen.get('withdraw_info')['info'];
                        if (detail_info.back_reason) {
                            $('#detailStatus').text(WITHDRAW_STATUS[choosen.get('status')]+'('+detail_info.back_reason+')');
                        } else {
                            $('#detailStatus').text(WITHDRAW_STATUS[choosen.get('status')]);
                        }
                        if (choosen.get('target_type') == 1) {
                            detailInfo = '姓名:' + withdraw_info.name[0] + '**' +
                                '<br>支付宝账号:' + withdraw_info.zfb +
                                '<br>手机号:' + withdraw_info.mobile;
                        } else if (choosen.get('target_type') == 0) {
                            detailInfo = '姓名:' + withdraw_info.name[0] + '**' +
                                '<br>银行卡号:' + withdraw_info.no.replace(/(\d{2})\d{7}/,"$1*******") +
                                '<br>开户行:' + withdraw_info.bankname +
                                '<br>手机号:' + withdraw_info.mobile.replace(/(\d{2})\d{5}/,"$1*****");
                        } else {
                            detailInfo = '无';
                        }
                        $('#detailInfo').html(detailInfo);
                        
                        var otherInfo = '';
                        if (detail_info.auto_trans_info) {
                            var trans_info = detail_info.auto_trans_info;
                            if (choosen.get('status') == 2) {
                                otherInfo = '兑换通道:' + trans_info.payer_no + '<br>交易流水号:' + trans_info.order_id + '<br>交易金额:' + trans_info.amount + '<br>交易日期:' + trans_info.pay_date;
                            } else if (choosen.get('status') == 4 || choosen.get('status') == 32) {
                                otherInfo = '错误码:' + trans_info.code + '<br>业务错误码:' + trans_info.sub_code + '<br>错误信息:' + trans_info.sub_msg + '<br>交易日期:' + trans_info.pay_date;
                            } else if (choosen.get('status') == 8) {
                                otherInfo = '交易正在进行中';
                            }
                        } else otherInfo = '无';
                        $('#otherInfo').html(otherInfo);
                        
                        var operateInfo = '';
                        var detail_info_obj = {
                            'system_check_info': {
                                'name': '系统审核时间',
                                'info': detail_info,
                                'date_field': 'incheck_time',
                                'reason': null
                            },
                            'manual_check_info': {
                                'name': '完成审核：',
                                'info': detail_info.manual_check_info,
                                'date_field': 'check_date',
                                'reason': 'reason',
                                'reason_root': detail_info.manual_check_info
                            },
                            'manual_auto_trans_info': {
                                'name': '人工审核通过：',
                                'info': detail_info.manual_auto_trans_info,
                                'date_field': 'pay_date',
                                'reason': null
                            },
                            'auto_trans_info':{
                                'name': '提交第三方：',
                                'info': detail_info.auto_trans_info,
                                'date_field': 'pay_date',
                                'reason': null
                            },
                            'auto_trans_info_complete':{
                                'name': '第三方完成：',
                                'info': detail_info.auto_trans_info,
                                'date_field': 'complete_pay_date',
                                'reason': null
                            },
                            'manual_forbidden_trans_info': {
                                'name': '禁止提现：',
                                'info': detail_info.manual_forbidden_trans_info,
                                'date_field': 'pay_date',
                                'reason': null
                            },
                            'back_trans_info': {
                                'name': '返款操作：',
                                'info': detail_info.back_trans_info,
                                'date_field': 'back_date',
                                'reason': 'back_reason',
                                'reason_root': detail_info
                            },
                            'manual_done_trans_info': {
                                'name': '手动完成提现：',
                                'info': detail_info.manual_done_trans_info,
                                'date_field': 'pay_date',
                                'reason': null
                            }
                        };
                        for (var key in detail_info_obj) {
                            if (detail_info_obj[key]['info']) {
                                var operation = '';
                                var trans_info = detail_info_obj[key]['info'];
                                if(trans_info) {
                                    var reason = detail_info_obj[key]['reason'];
                                    if (trans_info.admin_id) {
                                        if (trans_info.admin_id == 0) {
                                            var back_user = '系统';
                                        } else {
                                            var back_user = user_dict[trans_info.admin_id];
                                        }
                                    } else {
                                        var back_user = null;
                                    }
                                    if (back_user || trans_info[detail_info_obj[key]['date_field']]) {
                                        operation += detail_info_obj[key]['name'];
                                        if (back_user) operation += '  操作人- ' + back_user;
                                        if (reason) {
                                            var reason_root = detail_info_obj[key]['reason_root'];
                                            if(reason_root[reason]) {
                                                if(key == 'auto_trans_info_complete') operation += '(失败)';
                                                operation += '  原因- ' + reason_root[reason];
                                            }
                                        }
                                        if (trans_info[detail_info_obj[key]['date_field']])
                                            operation += '<br>受理日期：' + trans_info[detail_info_obj[key]['date_field']];
                                        operation += '<br><br>';
                                        operateInfo += operation;
                                    }
                                }
                            }
                        }
                        $('#operateInfo').html(operateInfo);
                        
                        if (detail_info.auto_risk) {
                            var riskInfo = detail_info.auto_risk;
                            if (typeof(riskInfo) == "string") {
                                $('#riskInfo').html(riskInfo);
                            } else {
                                if (detail_info.auto_risk) {
                                    var risk_info = '';
                                    var risk_size = 0;
                                     _.each(detail_info.auto_risk, function(v){
                                        risk_info += v+'<br>';
                                        risk_size++;
                                    })
                                } else {
                                    var risk_info = '-';
                                }
                                $('#riskInfo').html(risk_info);
                            }
                        }

                        $('#submitWithdraw, #finishWithdraw, #forbiddenWithdraw, #backWithdraw,' +
                            '#checkWithdraw, #uncheckWithdraw').hide();
                        if (choosen.get('status') == 1) {
                         $('#forbiddenWithdraw, #backWithdraw, #checkWithdraw, #uncheckWithdraw').show();
                        }
                        else if (choosen.get('status') == 4 || choosen.get('status') == 8) {
                         $('#forbiddenWithdraw, #backWithdraw').show();
                        }
                        else if (choosen.get('status') == 16) {
                          $('#backWithdraw').show();
                        }
                        $('#checkWithdraw').off('click').click(function() {
                            if(window.confirm('谨慎操作，请再次确认:\n')) {
                                $.post('/admin/withdraw/check/'+data_id+'/2/', JSON.stringify({'reason': ''})).done(function (resp) {
                                    var data = resp.data;
                                    $('#checkWithdraw, #uncheckWithdraw, #submitWithdraw').hide();
                                    $('#detailStatus').text(WITHDRAW_STATUS[8]);
                                    Backbone.history.loadUrl();
                                    notify.success('提示', '审核通过！等待自动提现。');
                                }).fail(function (data) {
                                    notify.notifyResp(data);
                                });
                            }
                        });
                        $('#uncheckWithdraw').off('click').click(function() {
                            var reason = window.prompt("请填写拒绝原因");
                            if(!reason){
                                alert("拒绝原因不能为空");
                            }
                            $.post('/admin/withdraw/check/'+data_id+'/4/', JSON.stringify({'reason': reason})).done(function (resp) {
                                var data = resp.data;
                                $('#uncheckWithdraw, #submitWithdraw').hide();
                                Backbone.history.loadUrl();
                                notify.success('提示', '审核未通过！请决定是否禁止提现。');
                            }).fail(function (data) {
                                notify.notifyResp(data);
                            });
                        });
                        $('#finishWithdraw').off('click').click(function() {
                            $.post('/admin/withdraw/'+data_id, JSON.stringify({"status": 2})).done(function (resp) {
                                var data = resp.data;
                                $('#checkWithdraw, #uncheckWithdraw, #finishWithdraw, #submitWithdraw').hide();
                                $('#detailStatus').text(WITHDRAW_STATUS[2]);
                                Backbone.history.loadUrl();
                                notify.success('提示', '更新成功！');
                            }).fail(function (data) {
                                notify.notifyResp(data);
                            });
                        });
                        $('#submitWithdraw').off('click').click(function() {
                            $.post('/admin/withdraw/'+data_id, JSON.stringify({'status': 8})).done(function (resp) {
                                var data = resp.data;
                                $('#checkWithdraw, #uncheckWithdraw, #submitWithdraw').hide();
                                $('#detailStatus').text(WITHDRAW_STATUS[8]);
                                Backbone.history.loadUrl();
                                notify.success('提示', '更新成功！等待自动提现。');
                            }).fail(function (data) {
                                notify.notifyResp(data);
                            });
                        });
                        $('#forbiddenWithdraw').off('click').click(function () {
                            $.confirm({
                                title: '禁止提现',
                                content: '确定禁止提现吗?',
                                confirmButton: '确认',
                                cancelButton: '取消',
                                icon: 'fa fa-warning',
                                theme: 'bootstrap',
                                backgroundDismiss: true,
                                keyboardEnabled: true,
                                confirmButtonClass: 'btn-danger',
                                confirm: function () {
                                    $.post('admin/withdraw/' + data_id, JSON.stringify({'status': 16})).done(function (resp) {
                                        var data = resp.data;
                                        $('#finishWithdraw, #checkWithdraw, #uncheckWithdraw, #submitWithdraw,' +
                                            '#forbiddenWithdraw').hide();
                                        $('#detailStatus').text(WITHDRAW_STATUS[16]);
                                        Backbone.history.loadUrl();
                                        notify.success('提示', '更新成功，该笔提现已被禁止.')
                                     }).fail(function(data){
                                        notify.notifyResp(data);
                                    })
                                },
                            });
                        });
                        $('#backWithdraw').off('click').click(function () {
                            var reason = window.prompt("请填写返款原因");
                            if(!reason){
                                alert("返款原因不能为空");
                            }
                            $.post('admin/withdraw/' + data_id, JSON.stringify({'status': 32, 'reason': reason})).done(function (resp) {
                                var data = resp.data;
                                $('#finishWithdraw, #checkWithdraw, #uncheckWithdraw, #submitWithdraw,' +
                                    '#forbiddenWithdraw, #backWithdraw').hide();
                                $('#detailStatus').text(WITHDRAW_STATUS[32]);
                                Backbone.history.loadUrl();
                                notify.success('提示', '更新成功，金额已返回到用户账户余额.')
                            }).fail(function(data){
                                notify.notifyResp(data)
                            })
                        });
                        $('#submitClose').off('click').click(function() {
                            Backbone.history.loadUrl();
                            $.magnificPopup.close();
                        });

                        var withdraw_no = '';
                        if (choosen.get('target_type') == 1) {
                            withdraw_no = withdraw_info.zfb;
                        } else if (choosen.get('target_type') == 0) {
                            withdraw_no = withdraw_info.no;
                        }

                        $.get('/admin/withdraw/'+choosen.get('target_type')+'/'+withdraw_no+'/duplicate/').done(function (resp) {
                            var data = resp.data;
                            var riskInfo = $('#riskInfo').html();
                            $('#riskInfo').html(riskInfo);
                        }).fail(function (data) {
                            notify.notifyResp(data);
                        });
                    },
                }
            });
            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || 'id',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    var newUrl = utils.composeQueryString('#op/withdraw_control/', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });
            $('.datetime-input').datetimepicker({
                format: 'YYYY-MM-DD HH:mm:ss',
            });
            $('.date-input').datetimepicker({
                format: 'YYYY-MM-DD',
            });
            utils.getPaginator(that.options, this.collection.total, '#op/withdraw_control/');
            return this;
        },
        load: function () {
            var that = this;
            this.user_collection.fetch({
                reset: true,
                data: {'disable_paginate': 1},
                success: function () {
                    that.collection.fetch({
                        reset: true,
                        data: that.options,
                        error: function (c, r, o) {
                            notify.notifyResp(r);
                            $('#content').append('<h4 class="text-muted">无数据</h4>');
                        },
                    });
                },
                error: function (c, r, o) {
                    notify.notifyResp(r);
                }
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/WithdrawControl.html",
        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            this.options.$size = 30;
            this.options.is_extend = true;
            this.options.$auto_risk = true;
            if(this.options.is_fresh === undefined) this.options.is_fresh = 1;
            var view = new WithdrawControlListView(this.options);
            view.template = this.template;
            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });

});
